package com.example.cart;

import static android.os.Environment.DIRECTORY_PICTURES;
import static android.os.Environment.DIRECTORY_RINGTONES;

import android.app.Application;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import androidx.room.Room;

import com.example.cart.dto.Goods;
import com.example.cart.repository.GoodsDao;
import com.example.cart.repository.factory.GoodsDataBase;
import com.example.cart.utils.Migration2to3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Observable;

public class CartApplication extends Application {


    private GoodsDataBase goodsDataBase;

    private static CartApplication cartApplication;

    public int getCartCount() {
        return CartCount;
    }

    private int CartCount;

    public static CartApplication get() {
        return cartApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("CartApplication","onCreate");
        goodsDataBase = Room.databaseBuilder(this, GoodsDataBase.class, "cart_db")
                // 允许在主线程main中执行SQL（仅用于测试）
                .allowMainThreadQueries()
                // 允许迁移数据库，否则实体发生变更时，会删除整张表及其中的数据，然后再创建新表
                .addMigrations(
                        new Migration2to3(2, 3)
                )
                .build();
        loadDataIntoDB();


        CartApplication.cartApplication = this;

        refreshCartCount();
    }

    private void loadDataIntoDB() {

        SharedPreferences record = getSharedPreferences("record", MODE_PRIVATE);
        boolean initiated = record.getBoolean("initiated", false);
        if (initiated) {
            return;
        }

        GoodsDao goodsDao = goodsDataBase.goodsDao();

        ArrayList<Goods> goods = new ArrayList<>();


        goods.add(new Goods(R.drawable.hp, "惠普", "打游戏啦", "hp.jpg", 5, "5999"));
        goods.add(new Goods(R.drawable.huawei, "华为电脑", "年薪百万", "huawei.jpg", 5, "4999"));
        goods.add(new Goods(R.drawable.jixie, "机械电脑", "打游戏就是好", "jixie.jpg", 5, "3899"));
        goods.add(new Goods(R.drawable.lenovo, "联想电脑", "爱国", "lenovo.jpg", 5, "5599"));
        goods.add(new Goods(R.drawable.yinben, "樱本电脑", "是初恋", "yinben.jpg", 5, "6999"));


        for (Goods good : goods) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), good.getId());

            File externalFilesDir = getExternalFilesDir(DIRECTORY_PICTURES);
            try {
                File file = new File(externalFilesDir, good.getImageSrc());
                if (file.createNewFile()) {

                }
                try (FileOutputStream outputStream = new FileOutputStream(file, false)) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                }
                good.setImageSrc(file.getAbsolutePath());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                bitmap.recycle();
            }


        }

        goodsDataBase.runInTransaction(() -> {

            for (Goods good : goods) {
                goodsDao.insert(good);
            }

        });

        record.edit().putBoolean("initiated", true).apply();
    }

    public GoodsDataBase getGoodsDataBase() {
        return goodsDataBase;
    }


    public void refreshCartCount() {
        CartCount = goodsDataBase.cartDao().count();
    }
}
